package com.tiger.cloud.service.rongyun;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tiger.cloud.common.rongyun.models.CodeSuccessResult;
import com.tiger.cloud.common.rongyun.models.GroupUser;
import com.tiger.cloud.common.rongyun.models.GroupUserQueryResult;
import com.tiger.cloud.common.rongyun.models.TokenResult;
import com.tiger.cloud.common.rongyun.service.RongCloud;
import com.tiger.cloud.dao.crm.UserDao;
import com.tiger.cloud.dao.sms.SmsGroupDao;
import com.tiger.cloud.dao.sms.SmsGroupUsersDao;
import com.tiger.cloud.model.crm.User;
import com.tiger.cloud.model.sms.SmsGroup;
import com.tiger.cloud.model.sms.SmsGroupUsers;
import com.tiger.cloud.util.IdWorker;
import com.tiger.cloud.util.Page;

@Service
public class RongYunApiService {
	
	private static final String APPKEY = "qd46yzrfqh5kf";
	private static final String APP_SECRET = "YxErsvwSuA";
	@Autowired
	private UserDao userDao;
	@Autowired
	private SmsGroupDao smsGroupDao;
	@Autowired
	private SmsGroupUsersDao smsGroupUsersDao;

	public TokenResult getRYToken(User user) throws Exception {
		TokenResult userGetTokenResult = null;
		boolean flag;
		RongCloud rongCloud = getRongCloud();
		if (rongCloud == null) {
			return userGetTokenResult;
		}
		try {
			userGetTokenResult = rongCloud.user.getToken(user.getId().toString(), user.getUserName(),
					user.getHeadImage());
			if (userGetTokenResult != null) {
				user.setRYToken(userGetTokenResult.getToken());
				flag = userDao.update(user) > 0;
				if (!flag) {
					return null;
				}
			}
		} catch (Exception e) {
			throw new Exception("获取token失败!===>" + e.getMessage().toLowerCase());
		}
		return userGetTokenResult;
	}

	public SmsGroup getGroup(String groupId) throws Exception {
		SmsGroup smsGroup = new SmsGroup();
		smsGroup.setGroupId(groupId);
		List<SmsGroup> smsGroups =smsGroupDao.findByEntity(smsGroup);
		return (smsGroups!=null&&smsGroups.size()>0)?smsGroups.get(0):null;
	}

	
	/**
	 * 创建群组方法
	 */
	public boolean createGroup(Long userId, String groupName, String image, String remark) throws Exception {
		RongCloud rongCloud = getRongCloud();
		CodeSuccessResult userRefreshResult = null;
		if (rongCloud == null) {
			return false;
		}
		String groupId="GROUP"+new IdWorker().getId();
		
		SmsGroup smsGroup = new SmsGroup();
		smsGroup.setName(groupName);
		smsGroup.setRemark(remark);
		smsGroup.setImage(image);
		smsGroup.setUserId(userId);
		smsGroup.setGroupId(groupId);
		if (smsGroupDao.insert(smsGroup) > 0) {
			SmsGroupUsers smsGroupUsers = new SmsGroupUsers();
			smsGroupUsers.setGroupId(smsGroup.getId());
			smsGroupUsers.setUserId(userId);
			if (smsGroupUsersDao.insert(smsGroupUsers) > 0) {
				try {
					userRefreshResult = rongCloud.group.create(new String[] { userId + "" }, smsGroup.getId() + "",
							groupName);
				} catch (Exception e) {
					throw new Exception("用户添加群聊失败===>" + e.getMessage().toLowerCase());
				}
				if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
					userRefreshResult = rongCloud.group.join(new String[] { userId + "" }, groupId + "", smsGroup.getName());
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 加入群组方法
	 */
	public boolean joinGroup(Long userId, String groupId) throws Exception {
		RongCloud rongCloud = getRongCloud();
		CodeSuccessResult userRefreshResult = null;
		if (rongCloud == null) {
			System.out.println("-------0------");
			return false;
		}
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			System.out.println("-------1------");
			return false;
		}
		SmsGroupUsers smsGroupUsers = new SmsGroupUsers();
		smsGroupUsers.setGroupId(smsGroup.getId());
		smsGroupUsers.setUserId(userId);
		if (smsGroupUsersDao.countByEntity(smsGroupUsers) > 0) {
			System.out.println("-------2------");
			return false;
		}
		if (smsGroupUsersDao.insert(smsGroupUsers) > 0) {
			try {
				System.out.println("-------3------");
				userRefreshResult = rongCloud.group.join(new String[] { userId + "" }, groupId + "", smsGroup.getName());
				System.err.println("-----------------------------------------------------");
				System.err.println(userRefreshResult);
				System.err.println("-----------------------------------------------------");
			} catch (Exception e) {
				throw new Exception("添加用户到群聊失败===>" + e.getMessage().toLowerCase());
			}
			if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
				return true;
			}
		}
		return false;
	}

	/**
	 * 退出群组方法
	 */
	public synchronized boolean quitGroup(Long userId, String groupId) throws Exception {
		RongCloud rongCloud = getRongCloud();
		CodeSuccessResult userRefreshResult = null;
		if (rongCloud == null) {
			return false;
		}
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			return false;
		}
		SmsGroupUsers findGroup =new SmsGroupUsers();
		findGroup.setUserId(userId);
		findGroup.setGroupId(smsGroup.getId());
		if (smsGroupUsersDao.countByEntity(findGroup)==1) {
			boolean codeSuccessResult= dismissGroup(userId, groupId);
			return codeSuccessResult;
		}
		SmsGroupUsers smsGroupUsers = new SmsGroupUsers();
		smsGroupUsers.setGroupId(smsGroup.getId());
		smsGroupUsers.setUserId(userId);
		if (smsGroupUsersDao.removeByEntity(smsGroupUsers) > 0) {
			try {
				userRefreshResult = rongCloud.group.quit(new String[] { userId + "" }, groupId + "");
				System.err.println("-----------------------------------------------------");
				System.err.println(userRefreshResult);
				System.err.println("-----------------------------------------------------");
			} catch (Exception e) {
				throw new Exception("退出群组失败===>" + e.getMessage().toLowerCase());
			}
			if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
				return true;
			}
		}
		return false;
	}

	/**
	 * 解散群组方法
	 */
	public boolean dismissGroup(Long userId, String groupId) throws Exception {
		RongCloud rongCloud = getRongCloud();
		CodeSuccessResult userRefreshResult = null;
		if (rongCloud == null) {
			return false;
		}
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			return false;
		}
		SmsGroupUsers smsGroupUsers = new SmsGroupUsers();
		smsGroupUsers.setGroupId(smsGroup.getId());
		smsGroupUsers.setUserId(userId);
		if (smsGroupUsersDao.removeByEntity(smsGroupUsers) > 0) {
			SmsGroup dleteGroup = new SmsGroup();
			dleteGroup.setId(smsGroup.getId());
			if (smsGroupDao.removeByEntity(dleteGroup) > 0) {
				try {
					userRefreshResult = rongCloud.group.dismiss(userId + "", groupId + "");
					System.err.println("-----------------------------------------------------");
					System.err.println(userRefreshResult);
					System.err.println("-----------------------------------------------------");
				} catch (Exception e) {
					throw new Exception("添加用户到群聊失败===>" + e.getMessage().toLowerCase());
				}
				if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 刷新群组信息方法
	 */
	public List<GroupUser> getGroupUsers(String groupId) throws Exception {
		RongCloud rongCloud = getRongCloud();
		GroupUserQueryResult userRefreshResult = null;
		if (rongCloud == null) {
			return null;
		}
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			return null;
		}
		try {
			userRefreshResult = rongCloud.group.queryUser(groupId);
			System.err.println("-----------------------------------------------------");
			System.err.println(userRefreshResult);
			System.err.println("-----------------------------------------------------");
		} catch (Exception e) {
			throw new Exception("添加用户到群聊失败===>" + e.getMessage().toLowerCase());
		}
		if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
			return userRefreshResult.getUsers();
		}
		return null;
	}

	/**
	 * 刷新群组信息方法
	 */
	public boolean refreshGroup(String groupId) throws Exception {
		RongCloud rongCloud = getRongCloud();
		CodeSuccessResult userRefreshResult = null;
		if (rongCloud == null) {
			return false;
		}
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			return false;
		}
		try {
			userRefreshResult = rongCloud.group.refresh(groupId + "", smsGroup.getName());
			System.err.println("-----------------------------------------------------");
			System.err.println(userRefreshResult);
			System.err.println("-----------------------------------------------------");
		} catch (Exception e) {
			throw new Exception("添加用户到群聊失败===>" + e.getMessage().toLowerCase());
		}
		if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
			return true;
		}
		return false;
	}

	/**
	 * 查询群成员方法
	 */
	public List<User> queryGroupUsers(String groupId) throws Exception {
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			return null;
		}
		SmsGroupUsers smsGroupUsers = new SmsGroupUsers();
		smsGroupUsers.setGroupId(smsGroup.getId());
		smsGroupUsers.setUserId(smsGroup.getUserId());
		return smsGroupUsersDao.findUsers(smsGroupUsers);
	}

	/**
	 * 邀请用户列表
	 */
	public Page<User> queryGroupUsers(String groupId,SmsGroupUsers smsGroupUsers) throws Exception {
		SmsGroup smsGroup =getGroup(groupId);
		if (smsGroup == null) {
			return null;
		}
		smsGroupUsers.setGroupId(smsGroup.getId());
		int limitStart=smsGroupUsers.getLimitStart(),limitEnd = smsGroupUsers.getLimitEnd();
		long count = smsGroupUsersDao.countPeerUsers(smsGroupUsers);
		Page<User> page = new Page<User>((int)(limitEnd/(limitEnd-limitStart)), (limitEnd-limitStart));
		page.setData(smsGroupUsersDao.findPeerUsers(smsGroupUsers));
		page.setTotalCount(count);
		return page;
		
	}
	
	public boolean refreshToken(User user) throws Exception {
		RongCloud rongCloud = getRongCloud();
		CodeSuccessResult userRefreshResult = null;
		if (rongCloud == null) {
			return false;
		}
		try {
			userRefreshResult = rongCloud.user
					.refresh(user.getId().toString(), user.getUserName(), user.getHeadImage());
			System.err.println("-----------------------------------------------------");
			System.err.println(userRefreshResult);
			System.err.println("-----------------------------------------------------");
		} catch (Exception e) {
			throw new Exception("刷新用户信息失败===>" + e.getMessage().toLowerCase());
		}
		if(userRefreshResult.getCode()!=null&&userRefreshResult.getCode().intValue()==200){
			return true;
		}
		return false;
	}

	private static RongCloud getRongCloud() {
		try {
			RongCloud rongCloud = RongCloud.getInstance(APPKEY, APP_SECRET);
			return rongCloud;
		} catch (Exception e) {
			return null;
		}
	}

	public List<SmsGroup> queryGroup(SmsGroup smsGroup) {
		return smsGroupDao.queryGroup(smsGroup);
	}
	
	public Boolean updateGroup(SmsGroup smsGroup) {
		return smsGroupDao.update(smsGroup)>0;
	}
 
}
